<script setup>
import { inject, ref } from "vue";
import { useCounterStore } from "@/stores/upgrade";
import { handleGoBack } from "@/utils/router";
import { productdetails } from "@/services/goods.js";

import { ordercheck, create, orderpay } from "@/services/pay";
import { addressList } from "@/services/user.js";
import { useaddressStore } from "@/stores/address";
import { mine, isPayPassApi, checkPayPass } from "@/services/user";
import { formatPrice } from "@/utils/formatPrice";
import { onLoad, onShow } from "@dcloudio/uni-app";

import wxicon from "@/static/cloudlibrary/icon_weixin.png";
import yeicon from "@/static/cloudlibrary/icon_yue.png";
import dficon from "@/static/cloudlibrary/icon_daifu.png";
// import xxicon from "../../upgrade/static/icon44.png";

const dateobj = useaddressStore();

onLoad((e) => {
  cart.value.push({
    product_id: e.id,
    product_num: 1,
  });

  // cart.value.product_id = e.id;
  form.value.cart = cart.value;

  // getprojectdet(e.id);
  // ordercheckfun();
});

onShow(() => {
  if (dateobj.address) {
    addressobj.value = JSON.parse(dateobj.address);
    form.value.address_id = addressobj.value.address_id;
  }
  isPayPassFun();
  ordercheckfun();
  // pay_type.value = balance.value < total_price.value ? 1 : 2;
});

const num = ref(0);
const totalnum = ref(0);
const dictorderpay = ref([]);
const seller = ref({});
const cart = ref([]);
const pay_type = ref("1");
const addressobj = ref({});
const balance = ref(0);
const total_price = ref(0);
const form = ref({
  mark: "",
  pay_type: pay_type.value,
  return_url: "",
  address_id: 0,
  order_type: "1",
});

const isoldpay = ref(true);
const ispayto = ref(0);

const order_id = ref(0);
const paymark = ref("");

async function getprojectdet(id) {
  const resdict = await productdetails({ id: id });
  dictorderpay.value = resdict.data;
}
async function ordercheckfun() {
  let res = null;
  try {
    res = await ordercheck({
      cart: cart.value,
      address_id: form.value.address_id,
      order_type: form.value.order_type,
    });
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    uni.navigateBack();
    return;
  }

  if (res.code != 200) {
    uni.showToast({
      title: res.info,
      icon: "none",
    });
    uni.navigateBack();
    return;
  }
  totalnum.value = 0;
  ispayto.value = res.data.is_pay_order;

  cart.value.forEach((element, index) => {
    totalnum.value += element.product_num;
  });

  dictorderpay.value = res.data.order_product;
  seller.value = res.data.seller;
  let arr = [];
  for (const key in res.data.order_type) {
    if (res.data.order_type.hasOwnProperty(key)) {
      arr.push(res.data.order_type[key]);
    }
  }

  // res.data.order_type
  columns.value[0] = arr;
  num.value = res.data.total_price;
  balance.value = res.data.user_balance.balance;
  if (balance.value < num.value) {
    form.value.order_type = "2";
    pay_type.value = "2";
  }

  addressobj.value = res.data.address;
  form.value.address_id =
    res.data.address && res.data.address.address_id
      ? res.data.address.address_id
      : "";
}
const paylist = ref([
  {
    title: "2",
    des: "微信支付（推荐）",
    icon: wxicon,
  },
  {
    title: "1",
    des: "余额支付 ",
    icon: yeicon,
  },
  // {
  //   title: "7",
  //   des: "他人代付",
  //   icon: dficon,
  // },
  // {
  //   title: "5",
  //   des: "线下缴费",
  //   icon: xxicon,
  // },
]);

const show = ref(false);

const showorder = ref(false);

const columns = ref([["sdsds", "asdasdsasd"]]);

const showpeiso = () => {
  show.value = true;
};
const showtext = () => {
  showorder.value = true;
};

const closefun = () => {
  show.value = false;
  showorder.value = false;
  showPassword.value = false;
  focusinput.value = false;
};
const configfun = () => {
  form.value.mark = paymark.value;
  showorder.value = false;
};

const isPayPass = ref(0);
const isPayPassFun = async () => {
  try {
    let res = await isPayPassApi();
    if (res.code == 200) {
      isPayPass.value = res.data;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const showPassword = ref(false);
const pay_pass = ref("");
const shoppayfun = async () => {
  //   const isoldpay = ref(true);
  // const ispayto=ref(0)

  // is_pay_order.value != 0 && isoldpay.value

  if (ispayto.value != 0 && isoldpay.value) {
    uni.showModal({
      title: "提示",
      content: "此商品已有未支付订单,是否继续支付购买",
      cancelText: "查看订单",
      confirmText: "确定下单",
      showCancel: true,
      success: ({ confirm, cancel }) => {
        if (confirm) {
          isoldpay.value = false;
          shoppayfun();
        }
        if (cancel) {
          uni.reLaunch({
            url: "/pages/order/orderlist/index?status=-2",
          });
        }
      },
    });

    return;
  }

  if (form.value.product_num <= 0) {
    uni.showToast({
      title: "商品数量不能为0",
      icon: "none",
    });
  }

  if (form.value.order_type == 0) {
    uni.showToast({
      title: "请选择配送方式",
      icon: "none",
    });
    return;
  }

  if (pay_type.value == 1 && balance.value < total_price.value) {
    uni.showToast({
      title: "余额不足，无法支付",
      icon: "none",
    });
    return;
  }

  form.value.pay_type = pay_type.value;
  let res = null;
  // if (pay_type.value == "2") {
  //   return uni.showToast({
  //     title: "暂未开通微信支付",
  //     icon: "none",
  //   });
  // }
  if (pay_type.value == 1 && isPayPass.value != 0) {
    if (!form.value.address_id) {
      uni.showToast({
        title: "用户地址不能为空",
        icon: "none",
      });
      return;
    } else {
      showPassword.value = true;
      pay_pass.value = "";
      setTimeout(() => {
        focusinput.value = true;
      }, 500);
    }

    return;
  } else if (pay_type.value == 1 && isPayPass.value == 0) {
    uni.showToast({
      title: "没有支付密码，前往设置",
      icon: "none",
    });
    setTimeout(() => {
      uni.navigateTo({
        url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
      });
    }, 500);
    return;
  }

  try {
    if (pay_type.value == "1") {
      // res = await create(form.value);
    }
    if (pay_type.value == "7") {
      form.value.is_negotiation = 1;
      form.value.pay_type = 1;
      form.value;
      res = await create(form.value);
    }

    if (pay_type.value == "2") {
      form.value.pay_type = 1;
      form.value.is_negotiation = 1;

      // #ifdef MP-WEIXIN
      res = await create(form.value);
      // #endif

      //#ifdef H5 || APP-PLUS
      uni.showToast({
        title: "暂未开通微信支付",
        icon: "none",
      });
      return;
      //#endif
    }

    if (pay_type.value == "5") {
      form.value.pay_type = 1;
      res = await create(form.value);
    }

    if (res.code == 200) {
      order_id.value = res.data.order_id;
      if (
        pay_type.value == "2" ||
        pay_type.value == "7" ||
        pay_type.value == "5"
      ) {
        paymentfun(res.data);
      }
    } else {
      uni.showToast({
        title: res.info,
        icon: "none",
      });
      pay_pass.value = "";
      return;
    }
  } catch (e) {
    pay_pass.value = "";
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};
const selecttype = ref(1);
const confirm = (e) => {
  selecttype.value = e.indexs[0] + 1;
  form.value.order_type = selecttype.value;
  show.value = false;
};
const changenumfun = () => {
  ordercheckfun();
};
function onBridgeReady(yishen, id) {
  WeixinJSBridge.invoke("getBrandWCPayRequest", yishen, (res) => {
    if (res) {
      uni.redirectTo({
        url: "/pages/goods/paystate/index?order_id=" + id,
      });
      // uni.showToast({
      //   title: "支付成功",
      // });
      // 使用以上方式判断前端返回,微信团队郑重提示：
      //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
    }
  });
}

const gocancle = () => {
  showPassword.value = false;
  pay_pass.value = "";
};

const ispay = ref(false);
const paymentfun = async () => {
  if (pay_type.value == "1") {
    // 防止小程序输入密码重复支付
    if (!ispay.value) {
      ispay.value = true;
    } else {
      return;
    }
    let res1 = await create(form.value);
    if (res1.code == 200) {
      order_id.value = res1.data.order_id;
    } else {
      uni.showToast({
        title: res1.info,
        icon: "none",
      });
      return;
    }
  }
  switch (pay_type.value) {
    case "1":
      try {
        let ress = await orderpay({
          pay_pass: pay_pass.value,
          order_id: order_id.value,
          pay_type: 1,
        });
        if (ress.code == 200) {
          uni.redirectTo({
            url: "/pages/goods/paystate/index?order_id=" + order_id.value,
          });
        } else {
          uni.showToast({
            title: ress.info,
            icon: "none",
          });
          pay_pass.value = "";

          uni.redirectTo({
            url: "/pages/goods/paystate/index?order_id=" + order_id.value,
          });
        }
      } catch (e) {
        uni.showToast({
          title: e.info,
          icon: "none",
        });
        pay_pass.value = "";
        uni.redirectTo({
          url: "/pages/goods/paystate/index?order_id=" + order_id.value,
        });
      }

      break;
    case "2":
      try {
        let res = null;
        // #ifdef H5 || APP-PLUS

        res = await orderpay({ order_id: order_id.value, pay_type: 2 });
        let yishen = JSON.parse(res.data.wxWcPayData);

        if (typeof WeixinJSBridge == "undefined") {
          if (document.addEventListener) {
            document.addEventListener(
              "WeixinJSBridgeReady",
              onBridgeReady(yishen, order_id.value),
              false
            );
          } else if (document.attachEvent) {
            document.attachEvent(
              "WeixinJSBridgeReady",
              onBridgeReady(yishen, order_id.value)
            );
            document.attachEvent(
              "onWeixinJSBridgeReady",
              onBridgeReady(yishen, order_id.value)
            );
          }
        } else {
          onBridgeReady(yishen, order_id.value);
        }

        // #endif
        // #ifdef MP-WEIXIN

        res = await orderpay({ order_id: order_id.value, pay_type: 3 });
        if (res.code == 200) {
          // 仅作为示例，非真实参数信息。
          uni.requestPayment({
            provider: "wxpay",
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            success: function (res) {
              // console.log("success:" + JSON.stringify(res));
              uni.redirectTo({
                url: "/pages/goods/paystate/index",
              });
            },
            fail: function (err) {
              uni.redirectTo({
                url: "/pages/goods/paystate/index?order_id=" + order_id.value,
              });
            },
          });
        } else {
          uni.redirectTo({
            url: "/pages/goods/paystate/index?order_id=" + order_id.value,
          });
        }

        // #endif
      } catch (e) {
        if (typeof WeixinJSBridge == "undefined") {
          uni.showToast({
            title: "支付失败！",
            icon: "none",
          });
          return;
        }
        uni.showToast({
          title: e.info,
          icon: "none",
        });
        ordercheckfun();
      }

      return;
      uni.redirectTo({
        url: "/pages/goods/paystate/index",
      });
      break;
    case "5":
      uni.redirectTo({
        url: `/pages/upgrade/offline_pay?order_id=${order_id.value}&price=${num.value}`,
      });
      break;
    case "7":
      // uni.redirectTo({
      //   url: "/pages/upgrade/payment/index?order_id=" + order_id.value,
      // });
      uni.redirectTo({
        url: "/pages/upgrade/payment/index?order_id=" + order_id.value,
      });

      break;
    default:
      break;
  }
};
//地址
function addressListfun() {
  if (!addressobj.value) {
    uni.navigateTo({
      url: "/pages/address_add/index?type=add",
    });
  }
}
const goselectaddressfun = () => {
  uni.navigateTo({
    url: "/pages/address/index?type=add",
  });
};

function getValue(item) {
  let res = JSON.parse(item);
}

const selectpaytype = (e) => {
  if (balance.value < num.value && e == 1) {
    uni.showToast({
      title: "余额不足",
      icon: "none",
    });
    return;
  }

  pay_type.value = e;
};

// 定义 finish 方法
const finish = async (e) => {
  pay_pass.value = e;
  try {
    let res = await checkPayPass({ pay_pass: pay_pass.value });
    if (res.code == 200) {
      paymentfun();
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    pay_pass.value = "";
  }
};

const forgot = () => {
  uni.navigateTo({
    url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
  });
};
const focusinput = ref(false);
</script>

<template>
  <view class="content">
    <view class="user-address">
      <view
        class="address-info-k"
        v-if="addressobj && addressobj.real_name"
        @click="goselectaddressfun"
      >
        <view class="address-info">
          <view class="address-info-name"
            ><text class="name">{{ addressobj.real_name }}</text
            ><text>{{ addressobj.phone }}</text></view
          >

          <view class="address-info-detail"
            >收货地址：{{
              addressobj.province +
              addressobj.city +
              addressobj.district +
              addressobj.detail
            }}</view
          >
        </view>
        <view>
          <up-icon name="arrow-right" color="#8C8C8C" size="32rpx"></up-icon>
        </view>
      </view>
      <view class="select-address" v-if="!addressobj" @click="addressListfun">
        <view class="select-address-add">
          <up-icon name="plus-circle" color="#01ADA8" size="24"></up-icon>
        </view>

        <view class="add-text">添加收货地址</view>
      </view>
    </view>
    <view class="goods">
      <view class="goods-shore">
        <image src="@/pages/goods/static/shore.png" mode="scaleToFill" />
        <text
          >我的供货商：{{
            seller && seller.name
              ? seller.name
              : seller.nickname
              ? seller.nickname
              : ""
          }}</text
        >
        <!-- <text class="gh-shore">更改供货商</text> -->
      </view>
      <view
        class="goods-info"
        v-for="(item, index) in dictorderpay"
        :key="index"
      >
        <view class="goods-info-img">
          <image :src="item.image" mode="scaleToFill" />
        </view>
        <view class="goods-info-detail">
          <view class="goods-info-detail-name">
            <view class="goods-name">{{ item.store_name || "" }}</view>
            <!-- <view class="goods-dec">商品名称</view> -->
          </view>
          <view class="goods-priceornum">
            <view class="goods-price"
              >会员价:<text> ¥{{ item.price }}</text></view
            >
            <view class="goods-num">
              <up-number-box
                bgColor="#ffffff"
                integer
                :min="1"
                :max="1000"
                v-model="cart[0].product_num"
                @change="changenumfun"
              ></up-number-box>
            </view>
          </view>
        </view>
      </view>
      <view class="goods-paylist">
        <view class="goods-paylist-item">
          <view class="goods-paylist-item-left">运费</view>
          <view class="goods-paylist-item-righ">0.00</view>
        </view>
        <view class="goods-paylist-item">
          <view class="goods-paylist-item-left">配送方式</view>
          <view class="goods-paylist-item-righ" @click="showpeiso"
            ><text class="color-select" v-if="selecttype == 1">{{
              columns[0][selecttype - 1] ? columns[0][selecttype - 1] : "请选择"
            }}</text>
            <text class="color-select" v-if="selecttype != 1">{{
              columns[0][selecttype - 1] ? columns[0][selecttype - 1] : "请选择"
            }}</text>
            <up-icon name="arrow-right" color="#01ADA8" size="32rpx"></up-icon
          ></view>
        </view>
        <view class="goods-paylist-item">
          <view class="goods-paylist-item-left">订单备注</view>
          <view class="goods-paylist-item-righ" @click="showtext"
            ><text
              class="color-select-mr"
              :class="form.mark ? 'color-select-mr-selet' : ''"
              >{{ form.mark ? form.mark : "无备注" }}
            </text>
            <up-icon name="arrow-right" color="#8C8C8C" size="32rpx"></up-icon
          ></view>
        </view>
      </view>
    </view>

    <view class="content-pay">
      <view
        class="content-pay-item"
        v-for="(item, index) in paylist"
        :key="index"
        @click="selectpaytype(item.title)"
      >
        <view
          :class="
            balance < num && item.title == 1
              ? 'content-pay-left noselect'
              : 'content-pay-left'
          "
        >
          <image :src="item.icon" mode="widthFix" />
          <text>{{ item.des }}</text>
          <text v-if="item.title == 1">(可用{{ formatPrice(balance) }}元)</text>
        </view>
        <view class="content-pay-right" v-if="pay_type == item.title">
          <image src="@/pages/goods/static/select.png" mode="widthFix" />
        </view>
      </view>
    </view>
  </view>

  <view class="content-footer">
    <view class="contebt-pays">
      <view>
        <text>共{{ totalnum }}件</text>
        <text class="pay-hj">合计:</text>
        <text class="pay-bq">¥</text>
        <text class="pay-num">{{ formatPrice(num) }}</text>
      </view>
      <!-- <up-button class="pay-bt" text="支付"></up-button> -->
      <view @click="shoppayfun" class="pay-bt pay-df">{{
        pay_type == 7 ? "找人帮忙代付" : "立即支付"
      }}</view>
    </view>
  </view>

  <up-picker
    :show="show"
    :columns="columns"
    closeOnClickOverlay="true"
    keyName="label"
    @cancel="closefun"
    @close="closefun"
    @confirm="confirm"
    @change="changeHandler"
  ></up-picker>
  <up-popup
    round="10"
    :show="showorder"
    @close="closefun"
    @cancel="closefun"
    @open="open"
  >
    <view class="popup-content">
      <view class="popup-content-bt">
        <text class="qx" @click="closefun">取消</text>
        <text>订单备注</text>
        <text class="qd" @click="configfun">确定</text>
      </view>
      <view class="popup-content-text">
        <up-textarea
          v-model="paymark"
          placeholder="请输入内容"
          count
          height="262rpx"
        ></up-textarea>
      </view>
    </view>
  </up-popup>

  <!-- 密码弹框 -->
  <view class="password_show">
    <u-popup
      :show="showPassword"
      mode="center"
      round="10"
      @close="closefun"
      @open="open"
    >
      <view class="password">
        <view class="popup-content-title">支付密码</view>
        <u-code-input
          v-model="pay_pass"
          :maxlength="6"
          dot
          size="80"
          @finish="finish"
          :focus="focusinput"
        ></u-code-input>
        <view class="footer">
          <view class="closefun" @click="showPassword = false">取消</view>
          <view class="forgot" @click="forgot">忘记密码？</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
